package com.duolaibei.business.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Selection;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.dialog.CollectTypeDialog;
import com.duolaibei.business.widget.DlKeyboard;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;

/**
 * Created by xlm on 2017/11/3 0003
 */

public class CollectActivity extends BaseActivity {

    @Inject(R.id.collect_input_edit)
    private EditText mEditInput;
    @Inject(R.id.collect_keyboard)
    private DlKeyboard dlKeyboard;
    @Inject(R.id.collect_realamount)
    private TextView mTextViewAmount;
    @Inject(R.id.back)
    private RelativeLayout mLayoutback;
    @Inject(R.id.title)
    private TextView mViewTitle;
    private final int REQUEST_CODE = 0;
    private boolean phoneTextCursor = false;
    private static final int TYPE_BANK = 1;
    private static final int TYPE_ALIPAY = 2;
    private static final int TYPE_WEIXIN = 3;
    private static final int TYPE_MORE = 4;

    private static int CURRENT_TYPE = -1;
    private static int COLLECT_TYPE_ONE = 1;
    private static int COLLECT_TYPE_TWO = 2;


    private static int COLLECT_TYPE = 0;

    private String appid;
    private String appsecret;
    private String code;
    private String amount;
    private String auth_code;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_collect);
    }

    @Override
    protected void initViews() {
        mViewTitle.setText("收款");
    }

    //    https://www.cnblogs.com/liuling/p/2015-9-21-1.html
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);

    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        // 设置不调用系统键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus = cls.
                    getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(mEditInput, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSetListener() {
        mLayoutback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mEditInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!dlKeyboard.isVisible()) {
                    dlKeyboard.show();
                }
                if (mEditInput.getText().toString().trim().length() > 0) {
                    //设置光标为可见状态
                    mEditInput.setCursorVisible(true);
                    phoneTextCursor = true;
                }
            }
        });

        dlKeyboard.setDlKeyboardListener(new DlKeyboard.OnKeyboardListener() {
            @Override
            public void clickTxt(String txt) {
                String num = mEditInput.getText().toString();
                num += txt;
                CommonUtil.checknum(num, mEditInput);
                mEditInput.setSelection(mEditInput.getText().toString().length());
                setRealAmount(mEditInput.getText().toString());
            }

            @Override
            public void clickConfirm() {
                checkPermission();
            }

            @Override
            public void clickBack() {
                // 点击删除按钮
                String num = mEditInput.getText().toString();
                if (num.length() > 0) {
                    StringBuffer sb = new StringBuffer(num.trim());
                    int index;
                    if (phoneTextCursor) {
                        index = mEditInput.getSelectionStart();
                        if (index > 0) {
                            sb = sb.delete(index - 1, index);
                        }
                    } else {
                        index = mEditInput.length();
                        if (index > 0) {
                            sb = sb.delete(index - 1, index);
                        }
                    }
                    mEditInput.setText(sb.toString());
                    if (index > 0) {
                        Selection.setSelection(mEditInput.getText(), index - 1);
                    }
                    if (mEditInput.getText().toString().trim().length() <= 0) {
                        mEditInput.setCursorVisible(true);
                        phoneTextCursor = false;
                    }
                    setRealAmount(mEditInput.getText().toString());
                }
            }

            @Override
            public void clickDelete() {
                mEditInput.setText("");
                setRealAmount("0.00");
            }

            @Override
            public void clickQrcode() {
                COLLECT_TYPE = 1;
                checkAmount();
            }
        });
    }

    private static final int PERMISSON_CAMERA = 0;

    private void checkPermission() {
        if (checkCameraPermission(PERMISSON_CAMERA)) {
            permissionOk();
        }
    }

    /**
     * 所有权限都已经获取
     */
    private void permissionOk() {
        COLLECT_TYPE = 2;
        checkAmount();
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToast("拒绝此权限，您将无法使用摄像头权限");
        }
    }

    private void setRealAmount(String amount) {
        mTextViewAmount.setText(amount);
    }

    private void scanCollectQrCode() {
        Intent intent = new Intent(getThis(), MyCaptureActivity.class);
        intent.putExtra("title", "扫码收款");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    auth_code = bundle.getString(CodeUtils.RESULT_STRING);
                    getPayData();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getThis(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
//            if (collectTypeDialog.isShowing()) {
//                collectTypeDialog.dismiss();
//            }
        }
    }

    /**
     * 检查输入金额，提交订单申请
     */
    private void checkAmount() {
        amount = mEditInput.getText().toString();
        if ("0".equals(amount)
                || "0.".equals(amount)
                || "0.0".equals(amount)
                || "0.00".equals(amount)
                || CommonUtil.isEmpty(amount)) {
            showToast("请输入有效金额");
        } else {
            switch (COLLECT_TYPE) {
                case 1:
                    getPayData();
                    break;
                case 2:
                    scanCollectQrCode();
                    break;
            }
        }
//        showPayTypeDialog(amount);
    }

    private CollectTypeDialog collectTypeDialog;

    private void showPayTypeDialog(String amount) {
        if (collectTypeDialog == null) {
            collectTypeDialog = new CollectTypeDialog(getThis());
        }
        collectTypeDialog.setCancelable(true);
        collectTypeDialog.setListener(new CollectTypeDialog.Listener() {
            @Override
            public void onSelectAlipy() {
                super.onSelectAlipy();
                scanCollectQrCode();
            }
        });
        if (!CommonUtil.isEmpty(amount)) {
            collectTypeDialog.setAmount(amount);
            collectTypeDialog.show();
        }
    }

    /**
     * 获取支付参数
     */
    private void getPayData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.PAYPARAM);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, "")));
        param.add("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
//                        "appid": "f033ab37c30201f73f142449d037028d",
//                        "appsecret": "yKR8ST3bL01iO2BmIqrZUovpWMEJhXDa",
//                        "code": "810036",
//                        "external_order_no": "CTHB074372997282D"
                        try {
                            JSONObject object = new JSONObject(string);
                            JSONObject object1 = object.getJSONObject("data");
                            appid = object1.optString("appid");

                            appsecret = object1.optString("appsecret");
                            code = object1.optString("code");
                            switch (COLLECT_TYPE) {
                                case 1:
                                    Intent intent = new Intent(getThis(), QrcodeCollectActivity.class);
                                    intent.putExtra("appid", appid);
                                    intent.putExtra("code", code);
                                    intent.putExtra("appsecret", appsecret);
                                    intent.putExtra("amount", amount);
                                    startActivity(intent);
                                    break;
                                case 2:
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            startPayOrder(auth_code, appid);
                                        }
                                    });
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        showToast(result.getInfo());
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }

    /**
     * 扫码支付
     *
     * @param auth_code
     */
    protected void startPayOrder(String auth_code, String appid) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.MICROPAY);
        param.add("appid", appid);
        param.add("total_amount", amount);
        param.add("code", code);
        param.add("auth_code", auth_code);
        param.add("sign", param.getMd5String(appsecret));
        HttpUtils.getInstance().url(ApiName.PAYAPI).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        Intent intent = new Intent(getThis(), OrderListActivity.class);
                        intent.putExtra("order_type", "all");
                        startActivity(intent);
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }


}
